package com.jinglvhuanjing.app;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;

import com.jinglvhuanjing.app.base.CountDownTianQiActivity;
import com.jinglvhuanjing.app.base.InstructionActivity;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.Constants;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.SpUtils;
import com.jinglvhuanjing.app.utils.StringUtils;
import com.jinglvhuanjing.app.widget.LeftDataView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.List;

import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends CountDownTianQiActivity implements EasyPermissions.PermissionCallbacks {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    /*** 读写权限 ***/
    private final String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private JzvdStd jzvdStd;

    private LeftDataView leftDataView;

    @Override
    public boolean isManagerActivity() {
        return false;
    }

    @Override
    public void countDownComplete() {
        LOG.e(TAG, "countDownComplete");
        start(leftDataView);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        this.jzvdStd = findViewById(R.id.video_player);
        this.leftDataView = findViewById(R.id.left_content_layout);

        LOG.openLog = SpUtils.getBoolean(getApplicationContext(), Constants.OPEN_LOG, false);
        findViewById(R.id.empty).setOnClickListener(view -> LoginActivity.startActivity(MainActivity.this));
//        SettingParamActivity.startActivity(this);
//        DeviceUtil.hideNavigation(getApplicationContext());

    }

    @Override
    protected void onResume() {
        super.onResume();
        setOnResume(true);
        if (!EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            EasyPermissions.requestPermissions(this, "程序运行需要存储权限", 0x00, PERMISSIONS);
        } else {
            loadVideo();
        }
    }


    private void loadVideo() {
        LOG.e(TAG, "loadVideo");
        createFile();
        setLeftView();
        start(leftDataView);

        String videoPath = Constants.SD_PATH + SpUtils.getString(getApplicationContext(), Constants.VIDEO_FILE_NAME);
        File videoFile = new File(videoPath);
        if(videoFile.exists()){
            JZDataSource jzDataSource = new JZDataSource(videoPath, "视频");
            jzDataSource.looping = true;
            jzvdStd.setUp(jzDataSource, Jzvd.SCREEN_NORMAL);
            jzvdStd.startVideo();
        }else{
            jzvdStd.setVisibility(View.GONE);
        }

//        test();
        write_lunxun();
        SerialMsgHandler.getInstance().setStartListenerLogin(this.mHandlerLogin);
    }

    /**
     * 1. 重写 Activity 的 onRequestPermissionsResult 方法
     *    主要是在该方法中使用 EasyPermissions 进一步处理权限申请后续结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(
                requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        LOG.e(TAG, "requestCode="+requestCode+"--perms="+perms.toString());
        if (perms.size() >= 2) {
            loadVideo();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
        setOnResume(false);
        Jzvd.clearSavedProgress(this, null);
        //home back
        Jzvd.goOnPlayOnPause();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Jzvd.releaseAllVideos();
    }

    private void createFile(){
        File file = new File(Constants.SD_PATH);
        if(!file.exists()){
            boolean create = file.mkdirs();
            Log.e(TAG, "path="+file.getPath());
            Log.e(TAG, "create="+create);
        }
        File config = new File(file.getPath() + "/" + Constants.configFile);
        if(!config.exists()){
            Constants.copyFromAssert(getApplicationContext(), Constants.configFile);
        }
        String jsonString = readTxt(file.getPath() + "/" + Constants.configFile);
        LOG.e(TAG, "jsonString="+jsonString);
        parseJson(jsonString);
    }

    private void parseJson(String j){
        try {
            JSONObject json = new JSONObject(j);
            String videoFileName = json.optString(Constants.VIDEO_FILE_NAME);
            String leftTitle = json.optString(Constants.LEFT_TITLE);
            String deviceId = json.optString(Constants.DEVICE_ID);
            String account = json.optString(Constants.ACCOUNT);
            String cityId = json.optString(Constants.CITYID);
            String serverIP = json.optString(Constants.SERVER_IP);
            String serverPort = json.optString(Constants.SERVER_PORT);
            String intervalTime = json.optString(Constants.INTERVAL_TIME);
            String version = json.optString(Constants.VERSION);
            String closeTime = json.optString(Constants.CLOSE_TIME);
            String openDoorEndIntervalTime = json.optString(Constants.OPEN_DOOR_END_INTERVAL_TIME);
            SpUtils.putString(getApplicationContext(), Constants.VIDEO_FILE_NAME, videoFileName);
            SpUtils.putString(getApplicationContext(), Constants.LEFT_TITLE, leftTitle);
            SpUtils.putString(getApplicationContext(), Constants.DEVICE_ID, deviceId);
            SpUtils.putString(getApplicationContext(), Constants.ACCOUNT, account);
            SpUtils.putString(getApplicationContext(), Constants.CITYID, cityId);
            SpUtils.putString(getApplicationContext(), Constants.SERVER_IP, serverIP);
            SpUtils.putString(getApplicationContext(), Constants.SERVER_PORT, serverPort);
            SpUtils.putString(getApplicationContext(), Constants.INTERVAL_TIME, intervalTime);
            SpUtils.putString(getApplicationContext(), Constants.VERSION, version);
            SpUtils.putString(getApplicationContext(), Constants.CLOSE_TIME, closeTime);
            SpUtils.putString(getApplicationContext(), Constants.OPEN_DOOR_END_INTERVAL_TIME, openDoorEndIntervalTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private String readTxt(String path){
        String str = "";
        try {
            File urlFile = new File(path);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(urlFile), "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            String mimeTypeLine = null ;
            while ((mimeTypeLine = br.readLine()) != null) {
                str = str+mimeTypeLine;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  str;
    }
}